﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using System.Data.SqlClient;
using Yipusoft.Account;

public partial class KeyUnitAdd : System.Web.UI.Page
{


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
           

            TabContainer1.ActiveTab = TabContainer1.Tabs[0];
           

           // TabContainer1.Tabs[1].Visible = false;
            ////得到登陆者所属支队或大队id
            string DepartmentID = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;
            //User.Identity.Name
            //string DepartmentID = "300100";

            //判断是大队还是支队,大队=显示派出所
            string group = "";
            if (group == "大队")
                ddlPoliceStations.Visible = true;
            if (group == "支队")
                ddlPoliceStations.Visible = false;

            try
            {
                DBCls db = new DBCls();
                DataTable dt = new DataTable();
                //读取本用户所在大队的派出所列表
                //DataTable dt = db.QueryDataTable("select DepartmentID,FullName from PoliceStationDepartments where ParentID='" + DepartmentID + "' ", "PoliceStation");
                //if (dt.Rows.Count > 0)
                //{
                //    ddlPoliceStations.Items.Clear();
                //    for (int i = 0; i < dt.Rows.Count; i++)
                //    {
                //        ddlPoliceStations.Items.Add(new ListItem(dt.Rows[i][1].ToString(), dt.Rows[i][0].ToString()));
                //    }
                //}
                lblDWGM_Police.Visible = false;
                ddlPoliceStations.Visible = false;
                //读取重点单位类型
                dt.Clear();
                dt = db.QueryDataTable("select KeyUnitTypeID,KeyUnitTypeDescript from KeyUnitType  order by cast( keyunittypeid  as int) ", "KeyUnitType");
                if (dt.Rows.Count > 0)
                {
                    ddlUnitType.Items.Clear();
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        ddlUnitType.Items.Add(new ListItem(dt.Rows[i][1].ToString(), dt.Rows[i][0].ToString()));
                    }
                }
                //重点单位类型对照表
                string sql = "select KeyUnitTypeDescript,KeyUnitTypeName from KeyUnitType order by cast( keyunittypeid  as int) ";
                SqlDataReader sqlReader = db.SqlReader(sql);

                DataTable Dt = new DataTable();
                DataRow dr;
                Dt.Columns.Add("KeyUnitTypeDescript", typeof(string));    //第几类
                Dt.Columns.Add("KeyUnitTypeName", typeof(string));   //类型全称



                while (sqlReader.Read())
                {
                    dr = Dt.NewRow();
                    dr[0] = sqlReader[0].ToString();
                    dr[1] = sqlReader[1].ToString();

                    Dt.Rows.Add(dr);
                }
                sqlReader.Close();
                this.DataList1.DataSource = new DataView(Dt);
                this.DataList1.DataBind();

                //判断此支队大队是否已输入 重点单位总数
                string sqlgetdid = "select * from KeyUnitCount where DepartmentID='" + DepartmentID + "'";

                DataTable dt2 = db.QueryDataTable(sqlgetdid, "DepartmentID");
                if (dt2.Rows.Count > 0)
                {
                    this.lblCount.Visible = false;
                    this.txtCount.Visible = false;
                }
                else
                {
                    this.lblCount.Visible = true;
                    this.txtCount.Visible = true;
                }

                //图片类型
                //rblImgType.Enabled = false;
                for (int i = 0; i < rblImgType.Items.Count; i++)
                {
                    rblImgType.Items[i].Enabled = false;
                }
                rblImgType.Items[0].Enabled = true;
               
            }
            catch
            {
                Response.Write("<script language=javascript>alert('页面绑定信息出错，请刷新.')</script>");
            }
        }
    }
    //保存重点单位信息
    protected void btnSave_Click(object sender, EventArgs e)
    {
        //得到登陆者所属支队或大队id
        string DepartmentID = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;
        //得到登陆者名称
        string username = User.Identity.Name;

        //string username = "liuzd";
        //string DepartmentID = "300100";

        string counts = txtCount.Text;//单位总数

        //派出所
        string police = string.Empty;
        if (ddlPoliceStations.Visible)
            police = ddlPoliceStations.SelectedValue.ToString();
        else
            police = "";

        string unitName = txtUnitName.Text;      //单位名称
        string state = RadioButtonList1.SelectedValue.ToString();   //是否完成
        string unitType = ddlUnitType.SelectedValue.ToString();     //单位类型
        string unitInfo = txtUnitInfo.Text;     //单位简介
        string info = txtPerformanceInfo.Text;  //完成情况

        DateTime dtime = DateTime.Now;



        try
        {
            if (CheckUnitNameIsSame(unitName))
            {
                Response.Write("<script language=javascript>alert('保存失败，此单位名称已存在！"+unitName+"')</script>");
                return;
            }

            DBCls db = new DBCls();

            //添加应完成总数
            string idd = System.Guid.NewGuid().ToString();
            string sql1 = "insert into KeyUnitCount values ('" + idd + "','" + DepartmentID + "'," + counts + ")";



            //添加重点单位
            string id = System.Guid.NewGuid().ToString();
            string sql2 = "insert into Performance values('" + id + "','" + username + "','" + police + "','" + unitName + "','" + unitInfo + "','" + state + "','" + info + "','" + dtime + "','" + DepartmentID + "','" + unitType + "')";

            bool rsl = false;

            if (txtCount.Visible)


                rsl = db.ExcuteSql2(sql1,sql2);

            else
                rsl = db.ExcuteSql1(sql2);

            if (rsl)
            {
                Response.Write("<script language=javascript>alert('保存成功！')</script>");
                //记录单位id
                ViewState.Add("PerformanceID", id);
                TabContainer1.Tabs[1].Visible = true;
                TabContainer1.ActiveTab = TabContainer1.Tabs[1];
                return;
            }
            else
            {
                Response.Write("<script language=javascript>alert('保存失败！请重新检查填写信息。"+rsl+"')</script>");
                return;
            }
        }
        catch
        {
            Response.Write("<script language=javascript>alert('数据保存失败！请重新检查填写信息。')</script>");
            return;
        }
    }
    //保存图片和说明
    protected void btnUpLoad_Click(object sender, EventArgs e)
    {
        string PerformanceID = string.Empty;
        try
        {
            //读取单位id
            PerformanceID = ViewState["PerformanceID"].ToString();
        }
        catch
        {
            TabContainer1.ActiveTab = TabContainer1.Tabs[0];
            Response.Write("<script language=javascript>alert('请先保存重点单位信息。')</script>");
            return;
        }
        //保存图片
        string path = string.Empty;
        bool img = SaveImg("", out path);
        if (img)
        {
            try
            {
                DBCls db = new DBCls();
                string id = System.Guid.NewGuid().ToString();
                string sql = "insert into PerformancePic values ('" + id + "','" + PerformanceID + "','" + path + "','" + txtDescript.Text + "','" + rblImgType.SelectedValue.ToString() + "')";
                if (db.ExcuteSql1_Tran(sql))
                {
                    //lblMsg="单位概貌以上传图片1张"，大于3时，下一图片类型显示和当前可选
                    /*
                     * 
                     * 1.19号
                     * 
                     */
                    Response.Write("<script language=javascript>alert('图片保存成功。')</script>");
                    //重新绑定并显示图片和说明
                    BindDateList(PerformanceID);
                }
            }
            catch (Exception ex)
            {

                {
                    //删除图片
                }
                Response.Write("<script language=javascript>alert('图片保存失败！请重新上传。')</script>");
            }
        }
        else
        {
            Response.Write("<script language=javascript>alert('图片格式不正确，请上传 *.bmp,*.jpg,*.jpeg 格式图片')</script>");
        }

    }
    /// <summary>
    /// 绑定显示图片和说明
    /// </summary>
    void BindDateList(string PerformanceID)
    {
        DBCls db = new DBCls();
        string sql = "select PerformancePicID,PictureUrl,PictureDescript,PictureType from PerformancePic where PerformanceID='" + PerformanceID + "' order by case PictureType when '单位概貌' then 1 when '检查和整改火灾隐患' then 2 when '扑救初期火灾' then 3 when '组织引导人员疏散逃生' then 4 when '消防安全知识宣传教育培训' then 5 end ";
        SqlDataReader sqlReader = db.SqlReader(sql);

        DataTable Dt = new DataTable();
        DataRow dr;
        Dt.Columns.Add("PerformancePicID", typeof(string));    //主键
        Dt.Columns.Add("PictureUrl", typeof(string));   //图片地址
        Dt.Columns.Add("PictureDescript", typeof(string));   //图片描述
        Dt.Columns.Add("PictureType", typeof(string));    //图片类型

        int gm=0;
        int jc=0;
        int pj=0;
        int zz = 0;
        int xf = 0;

        while (sqlReader.Read())
        {
            dr = Dt.NewRow();

            string type = sqlReader[3].ToString();

            dr[0] = sqlReader[0].ToString();
            dr[1] = sqlReader[1].ToString();
            dr[2] = sqlReader[2].ToString();
            dr[3] = type;
            Dt.Rows.Add(dr);

            if (type.Contains("概貌"))
            {
                gm += 1;
                if (gm > 3)
                    rblImgType.Items[1].Enabled = true;
            }
            else if (type.Contains("检查"))
            {
                jc += 1;
                if (jc > 3)
                    rblImgType.Items[2].Enabled = true;
            }
            else if (type.Contains("扑救"))
            {
                pj += 1;
                if (pj > 3)
                    rblImgType.Items[3].Enabled = true;
            }
            else if (type.Contains("组织"))
            {
                zz += 1;
                if (zz > 3)
                    rblImgType.Items[4].Enabled = true;
            }
            else if (type.Contains("消防"))
            {
                xf += 1;
            }
        }
        string s = "已上传图片数：";
        lblGM.Text = s+gm;
        lblJC.Text = s + jc;
        lblPJ.Text = s + pj;
        lblZZ.Text = s + zz;
        lblXF.Text = s + xf;

        sqlReader.Close();
        this.DltList.DataSource = new DataView(Dt);
        this.DltList.DataBind();
    }
    /// <summary>
    /// 上传图片
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    private bool SaveImg(string name1, out string localPath)
    {
        HttpFileCollection files = HttpContext.Current.Request.Files;
        System.Text.StringBuilder strMsg = new System.Text.StringBuilder();

        bool fileOK = false;
        HttpPostedFile postedFile = files[0];

        string fileName, fileExtension;
        fileName = System.IO.Path.GetFileName(postedFile.FileName);
        if (fileName != "")
        {
            fileExtension = System.IO.Path.GetExtension(fileName);
            String[] allowedExtensions = { ".bmp", ".jpg",".jpeg" };
            for (int i = 0; i < allowedExtensions.Length; i++)
            {
                if (fileExtension.ToLower() == allowedExtensions[i])
                {
                    fileOK = true;
                    break;
                }
            }
        }
        if (fileOK)
        {

            //Bitmap bm = new Bitmap(path);
            //本地image文件夹路径
            string sPath = System.Web.HttpContext.Current.Request.MapPath("UpLoadImages/");
            //文件扩展名
            fileExtension = System.IO.Path.GetExtension(fileName).ToLower();
            //随机文件名
            Random rnd = new Random();
            string newName = DateTime.Now.ToString().Replace("-", "").Replace(":", "").Replace(" ", "") + rnd.Next(1000).ToString();
            localPath = "UpLoadImages/" + newName + fileExtension;
            postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath("UpLoadImages/") + newName + fileExtension);

            return true;

        }
        else
        {
            //提示
            localPath = "";
            return false;
        }

    }
    protected void btnImgDel_Click(object sender, EventArgs e)
    {

    }
    protected void btnImgDel_Command(object sender, CommandEventArgs e)
    {
        if (e.CommandArgument == null)
            return;
        string id = e.CommandArgument.ToString();
        DBCls db = new DBCls();
        try
        {
            string performanceid = ViewState["PerformanceID"].ToString();

            string sqls = "select picturetype from performancepic where performanceid='" + performanceid + "' and  picturetype = ( select picturetype from performancepic where performancepicid='" + id + "')";
            DataTable dt = db.QueryDataTable(sqls, "pics");
            if (dt.Rows.Count < 5)
            {
                Response.Write("<script language=javascript>alert('图片类型 "+dt.Rows[0][0].ToString()+" 的图片不得少于4张，删除前请先上传足够的图片。')</script>");
                return;
            }
            if (db.ExcuteSql1_Tran("delete PerformancePic where PerformancePicID='" + id + "'"))
            {
                Response.Write("<script language=javascript>alert('删除成功。')</script>");
                BindDateList(performanceid);
            }
        }
        catch
        {
            Response.Write("<script language=javascript>alert('删除失败。')</script>");
        }
    }
    /// <summary>
    /// 查询是否存在同名重点单位。存在=true；不存在=false
    /// </summary>
    /// <param name="unitname"></param>
    /// <returns></returns>
    private bool CheckUnitNameIsSame(string unitname)
    {
        DBCls db = new DBCls();
        string sql = "select performanceid from performance where keyunitname = '" + unitname + "'";
        DataTable dt = db.QueryDataTable(sql, "issame");
        if (dt.Rows.Count > 0)
            return true;
        else
            return false;
    }
}
